package com.letere.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.letere.bean.Result;
import com.letere.bean.User;
import com.letere.service.UserService;
import com.letere.util.JwtUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author letere
 * @create 2021-02-04 17:43
 */
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation("登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", required = true),
            @ApiImplicitParam(name = "password", value = "密码", required = true)
    })
    @PostMapping("/user/login")
    public Result login(String username, String password) {
        //获取用户信息
        User user = userService.getUserById(1);
        //比较传入信息与用户信息
        if(username.equals(user.getUsername())) {
            if (password.equals(user.getPassword())) {
                return Result.success(JwtUtil.create(user));
            }
            return Result.failure("密码错误！");
        }
        return Result.failure("用户名错误！");
    }

    @ApiOperation("更新用户信息")
    @ApiImplicitParam(name = "message", value = "Json字符串（用户信息）", required = true)
    @PostMapping("/user/update")
    public void updateUser(String message,  @RequestBody MultipartFile file) throws IOException {
        //解析Json字符串
        ObjectMapper om = new ObjectMapper();
        User user = om.readValue(message, User.class);
        //读取文件字节
        byte[] bytes = file.getBytes();
        user.setAvatar(bytes);
        //更新信息
        userService.updateUser(user);
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/user/detail")
    public Result getUserDetail() {
        User user = userService.getUserById(1);
        return Result.success(user);
    }
}
